/*
 * Created on 2005-9-21
 * Last modified on 2006-11-21
 * www.YeQiangWei.com
 */

package com.yeqiangwei.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

import com.yeqiangwei.util.Validator;

/**
 * 
 * @author YeQiangWei by 我容易么我
 * Powered by YeQiangWei.com
 */
public class URL{

	private final static Logger logger= Logger.getLogger(URL.class.getName());
	

	/**
     * 对URL中文进行转码 一般get方式查询参数用到
     * @param str 中文字符串
     * @param coder 编码方式，如 UTF-8\GBK
     * @return
     */
    public static String urlEncoder(String str, String coder){
        if(Validator.isEmpty(str)){
            return "";
        }
        if(Validator.isEmpty(coder)){
            coder = "UTF-8";
        }
        try {
            str = java.net.URLEncoder.encode(str, coder);
        } catch (UnsupportedEncodingException e) {
            str = "";
            logger.error(e.toString());
        }
        return str;
    }
    
    
    /**
     * 对URL中文进行反转码，一般get方式查询参数用到
     * @param str 中文字符串
     * @param coder 编码方式，如 UTF-8\GBK
     * @return
     */
    public static String urlDecoder(String str, String coder){
        if(Validator.isEmpty(str)){
            return "";
        }
        if(Validator.isEmpty(coder)){
            coder = "UTF-8";
        }
        try {
            str = java.net.URLDecoder.decode(str, coder);
        } catch (UnsupportedEncodingException e) {
            str = "";
            logger.error(e.toString());
        }
        return str;
    }
    

    /**
     * 取得请求带参数的URL的方法
     * @param request
     * @return
     */
    public static String getUrl(HttpServletRequest request) {
        StringBuffer originalURL = request.getRequestURL();
        Map parameters = request.getParameterMap();
        if (parameters != null && parameters.size() > 0) {
            originalURL.append("?");
            for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String[] values = (String[]) parameters.get(key);
                for (int i = 0; i < values.length; i++) {
                    originalURL.append(key).append("=").append(values[i]).append("&");
                }
            }
        }
        return originalURL.toString();
    } 
    
    
    /**
     * 取得基于主机名的url，定向根目录的域名。（端口自动识别）
     * @param request
     * @return
     */
    public static String getServerUrl(HttpServletRequest request) {
        String str = "http://" + request.getServerName();
        int port = request.getServerPort();
        if(port!=80){
            str = str + ":" + String.valueOf(port);
        }
        return str;
    } 
    
    
    /**
     * 根据提供的域名地址返回网页html内容
     * @param domain
     * @return
     */
    public static String getWebContent(String domain){
    	StringBuffer sb = new StringBuffer("");
		BufferedReader in = null;
		java.net.URL url = null;
        try{  
            url = new java.net.URL(domain);
            in =  new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
            String line;
            while((line = in.readLine()) != null){
                sb.append(line);
            }
        }catch(Exception e) {
           logger.error(domain+e.toString());
        }finally{
        	try {
				in.close();
			} catch (IOException e) {
				logger.error(e.toString());
			}
        }
        if(sb.length()>0){
        	return sb.toString();
        }else{
        	return null;
        }
    }
    
    public static String getWebContent2(String domain, String encoding){
    	StringBuffer sb = new StringBuffer("");
		BufferedReader in = null;
		java.net.URL url = null;
        try{  
        	url = new java.net.URL(domain);    
            in = new BufferedReader(new InputStreamReader(url.openStream(),encoding));
            String line;
            while((line = in.readLine()) != null){
                sb.append(line);
            }
        }catch(Exception e) {
        	 logger.error(domain+e.toString());
        }finally{
        	try {
				in.close();
			} catch (IOException e) {
				logger.error(e.toString());
			}
        }
        return sb.toString();
    }
    /**
     * 指定编码类型的
     * @param domain 
     * @param encoding 编码类型
     * @return
     * 2005-12-11 18:21:14 Made In YeQiangWei
     * com.yeqiangwei.net
     */
    public static String getWebContent(String domain, String encoding){
        StringBuffer sb = new StringBuffer("");
        try {
 			sb.append(new String(HttpWrapper.getBytes(domain),encoding));
		} catch (UnsupportedEncodingException e) {
			logger.error(e.toString() + domain);
		}
		/*
		BufferedReader in = null;
		java.net.URL url = null;
        try{  
        	url = new java.net.URL(domain);    
            in = new BufferedReader(new InputStreamReader(url.openStream(),encoding));
            String line;
            while((line = in.readLine()) != null){
                sb.append(line);
            }
        }catch(Exception e) {
        	 logger.error(domain+e.toString());
        }finally{
        	try {
				in.close();
			} catch (IOException e) {
				logger.error(e.toString());
			}
        }
        */
        return sb.toString();         
    }
 
    public static String getHeader(HttpServletRequest request,
            String str){
    	String s = "";
    	try{
    		s = request.getHeader(str);
    	}catch(Exception e){
    		logger.error(e.toString());
    	}
    	return s;
    }      
    
    /*
    public static String getContent(String host, int port){
    	SocketChannel channel = null;
    	InetSocketAddress socketAddress	= new InetSocketAddress(host, 80);
    	Charset charset = Charset.forName("UTF-8");
    	CharsetDecoder decoder = charset.newDecoder();
    	CharsetEncoder encoder = charset.newEncoder();
    	// Allocate buffers 
    	ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    	CharBuffer charBuffer = CharBuffer.allocate(1024);

    	// Connect 
    	try {
			channel = SocketChannel.open();
			channel.configureBlocking(false);
			channel.connect(socketAddress);
			channel.socket().bind(socketAddress);
			Selector selector = Selector.open();
			channel.register(selector,SelectionKey.OP_READ);
			
			

	    	// Send request 
	    	String request =  "GET "+host+" HTTP/1.0"+"\n\r\n\r";	    	
	    	
	    	while (selector.select(500) > 0) {
	    		Set readyKeys = selector.selectedKeys();
	    		Iterator readyItor = readyKeys.iterator();
	    		while (readyItor.hasNext()) {
		    		SelectionKey key = (SelectionKey)readyItor.next();
		    		readyItor.remove();
		    		SocketChannel keyChannel = (SocketChannel)key.channel();
		    		if (key.isConnectable()) {
			    		if (keyChannel.isConnectionPending()) {
			    			keyChannel.finishConnect();
			    		}
			    		keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
			    	}
		    		else if (key.isReadable()) {
			    		keyChannel.read(buffer);
			    		buffer.flip();
			    		decoder.decode(buffer, charBuffer, false);
			    		charBuffer.flip();
			    		System.out.print(charBuffer);
			    		buffer.clear();
			    		charBuffer.clear();
			    	} else {
			    		System.err.println("Ooops");
		    		}
	    		}
	    	}
	    	
		} catch (IOException e) {
			logger.error(e.toString());
		}finally {
			if (channel!=null) {
				try {
					channel.close();
				} catch (IOException e2){
					logger.error(e2.toString());
				}
			}
		}
		return host;
    }
    */
    
    
   
    public static void main(String args[]){

    	String s = URL.getWebContent("http://www.yeqiangwei.com");
    	System.out.println(s);

    }
  
}
